package lxs.swift.tool.http;


import java.util.concurrent.atomic.AtomicBoolean;

public class SegSender extends Sender {
    private final String prefix;
    private final String separator;
    private final String suffix;
    private final AtomicBoolean isFirst = new AtomicBoolean(true);

    public SegSender(Config config, String prefix, String separator, String suffix) {
        super(config);
        this.prefix = prefix;
        this.separator = separator;
        this.suffix = suffix;
    }

    @Override
    protected void open() {
        super.open();
        super.write(this.prefix.getBytes(super.config.charset));
    }

    public Receiver read() {
        super.write(this.suffix.getBytes(super.config.charset));
        return super.read();
    }

    public Sender send(String item) {
        byte[] bytes = item.getBytes(super.config.charset);
        if (!isFirst.get()) super.write(separator.getBytes(super.config.charset));
        else isFirst.set(false);
        super.write(bytes);
        return this;
    }
}
